package com.yancloud.android.reflection.get;

import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.yancloud.android.manager.IAppConnector;
import com.yancloud.android.manager.PackageVersionPair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by root on 6/29/17.
 */

public class AppConnectorImpl extends IAppConnector.Stub {
    Map<String, Task> id2Task;
    Map<String, IBinder> pkg2Server;
    Map<String, Long> packages;

    public AppConnectorImpl() {
        id2Task = new HashMap<>();
        packages = new HashMap<>();
        pkg2Server = new HashMap<>();
    }

    @Override
    public void register(String pkgName,String version, IBinder binder) throws RemoteException {
        if (pkgName != null) {
            pkg2Server.put(pkgName, binder);
            packages.put(pkgName,System.currentTimeMillis());
        }
        String cid = allocCID();
        Log.d("PkgProvider", " register, cid:" + cid + " pkgName:" + pkgName + " binderisNull:" + (binder == null));
        return;
    }

    private static AtomicInteger gCID = new AtomicInteger(0);

    private String allocCID() {
        return gCID.incrementAndGet() + "";
    }

    public static ExecutorService executor = Executors.newFixedThreadPool(5);

    @Override
    public IBinder request(String pkgName,String version) throws RemoteException {
        return pkg2Server.get(pkgName);
    }

    @Override
    public List<PackageVersionPair> listPackages() throws RemoteException {
       List<PackageVersionPair> ret = new ArrayList<>();

        for (String key:packages.keySet()){
            IBinder binder = pkg2Server.get(key);
            if (binder!=null && binder.isBinderAlive())
                ret.add(new PackageVersionPair(key,packages.get(key)+""));
            else
                pkg2Server.remove(key);
        }
        return ret;
    }

    public static int globalID = 0;

    private String allocID() {
        synchronized (this) {
            return globalID++ + "";
        }
    }
}
